<?php

namespace app\api\model\kuyou\applet;

use app\api\controller\kuyou\applet\Commons;
use think\Model;
use think\Db;
use Exception;
class Inventory extends Model
{

    // 表名
    protected $name = 'kuyou_inventory';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    /**
     * 获取列表
     * @param array $where
     * @param int $page
     * @param int $limit
     * @return array
     */
    public static function getList($where,$page,$limit,$sort_field,$sort_type){
        $app_page = config('app_page');
        $app_page = $app_page===false?false:true;
        $pageStatus = true;
        if($app_page){
            if($page<0){
                $pageStatus = false;
            }
        }
        if($pageStatus){
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->order($sort_field,$sort_type)->page($page,$limit)->field("id,purchase_code,store_type,result,FROM_UNIXTIME(purchase_time,'%Y-%m-%d') as purchase_time")->select())->toArray();
        }else{
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->order($sort_field,$sort_type)->field("id,purchase_code,store_type,result,FROM_UNIXTIME(purchase_time,'%Y-%m-%d') as purchase_time")->select())->toArray();
        }
        foreach ($list as $list_k=>$list_v){
            $list[$list_k]['py_list'] = Db::name('kuyou_warehousing')->where(['order_type'=>'1','order_id'=>$list_v['id']])->column('purchase_code');
            $list[$list_k]['pk_list'] = Db::name('kuyou_warehouse')->where(['order_type'=>'1','order_id'=>$list_v['id']])->column('purchase_code');

            $info = Db::name('kuyou_inventory_info')->where(['purchase_code'=>$list_v['purchase_code']])->select();
            $py = 0;$pk = 0;
            foreach ($info as $info_k=>$info_v){
                if($info_v['profit']>0){
                    $py = 1;
                }else if($info_v['profit']<0){
                    $pk = 1;
                }
            }
            $list[$list_k]['py'] = $py;
            $list[$list_k]['pk'] = $pk;
        }
        $count = self::where(function ($query) use ($where) {
            $query->where($where);
        })->count();

        return ['list'=>$list,'count'=>$count];
    }

    /**
     * 获取盘点数据
     * @return array
     */
    public static function stockList($where){
        $list = Db::name('kuyou_goods_stock')->alias('gs')
            ->join('kuyou_goods g','g.id=gs.goods_id')
            ->where(['g.serial'=>['<>','1']])
            ->where($where)
            ->group('gs.goods_code,gs.attribute_id,gs.stores_id')
            ->field('sum(gs.stock) as stock,sum(gs.cost_money) as cost_money,gs.goods_code,gs.attribute_id,gs.stores_id')
            ->order('gs.goods_code ASC')
            ->select();

        foreach ($list as $list_k=>$list_v){
            $goods = Db::name('kuyou_goods')->where(['goods_code'=>$list_v['goods_code']])->field('id,goods_name,goods_code,note,goods_type_id,goods_specification_id,unit_id')->find();
            $goods_type = Db::name('kuyou_goods_type')->where(['id'=>$goods['goods_type_id']])->field('id,supplier_type_name')->find();
            $stores = Db::name('kuyou_stores')->where(['id'=>$list_v['stores_id']])->field('id,name')->find();
            $list[$list_k]['goods'] = $goods;
            $list[$list_k]['goods_type'] = $goods_type;
            $list[$list_k]['stores'] = $stores;

            $attribute_ids = Db::name('kuyou_aux_combination')->where(['id'=>$list_v['attribute_id']])->value('attr_ids');
            if($attribute_ids){
                $attribute_ids = explode('&',$attribute_ids);
                $attribute = Db::name('kuyou_auxiliary')->where(['id'=>['in',$attribute_ids]])->column('name');
                $attribute_name = implode('/',$attribute);
                $list[$list_k]['attr_name'] = $attribute_name;
            }else{
                $list[$list_k]['attr_name'] = '';
            }

            $goods_attr = Db::name('kuyou_goods_attr')->where(['goods_code'=>$list_v['goods_code'],'attribute_id'=>$list_v['attribute_id']])->value('id');
            $list[$list_k]['attr_id'] = $goods_attr;

            $unit = Db::name('kuyou_unit')->where(['id'=>$goods['unit_id']])->value('name');
            $list[$list_k]['unit_name'] = $unit;
        }
        return ['list'=>$list];
    }

    /**
     * 获取详情
     * @param string $purchase_code
     * @return array
     */
    public static function getDetail($purchase_code,$where){
        $detail = self::where(function ($query) use ($purchase_code) {
            $query->where('purchase_code', '=', $purchase_code);
        })->field("id,purchase_code,store_type,result,FROM_UNIXTIME(purchase_time,'%Y-%m-%d') as purchase_time")->find();
        if($detail){
            $info_list = Db::name('kuyou_inventory_info')
                ->where($where)
                ->where(['purchase_code'=>$detail['purchase_code']])
                ->field('purchase_code,FROM_UNIXTIME(purchase_time,\'%Y-%m-%d\') as purchase_time,goods_type,goods_id,stores_id,goods_attr,stock,invertory_stock,profit')->select();
            foreach ($info_list as $list_k=>$list_v){
                $goods = Db::name('kuyou_goods')->where(['id'=>$list_v['goods_id']])->field('id,goods_name,goods_code,note,goods_type_id,goods_specification_id,unit_id')->find();
                $goods_type = Db::name('kuyou_goods_type')->where(['id'=>$goods['goods_type_id']])->field('id,supplier_type_name')->find();
                $stores = Db::name('kuyou_stores')->where(['id'=>$list_v['stores_id']])->field('id,name')->find();
                $info_list[$list_k]['goods'] = $goods;
                $info_list[$list_k]['goods_type'] = $goods_type;
                $info_list[$list_k]['stores'] = $stores;

                $attribute_id = Db::name('kuyou_goods_attr')->where(['id'=>$list_v['goods_attr']])->value('attribute_id');
                $attribute_ids = Db::name('kuyou_aux_combination')->where(['id'=>$attribute_id])->value('attr_ids');
                if($attribute_ids){
                    $attribute_ids = explode('&',$attribute_ids);
                    $attribute = Db::name('kuyou_auxiliary')->where(['id'=>['in',$attribute_ids]])->column('name');
                    $attribute_name = implode('/',$attribute);
                    $info_list[$list_k]['attr_name'] = $attribute_name;
                }else{
                    $info_list[$list_k]['attr_name'] = '';
                }

                $goods_attr = Db::name('kuyou_goods_attr')->where(['goods_code'=>$goods['goods_code'],'attribute_id'=>$list_v['goods_attr']])->value('id');
                $info_list[$list_k]['attr_id'] = $goods_attr;

                $unit = Db::name('kuyou_unit')->where(['id'=>$goods['unit_id']])->value('name');
                $info_list[$list_k]['unit_name'] = $unit;
            }
            $detail['info_list'] = $info_list;
        }else{
            return ['status'=>500,'msg'=>'未查询到相关数据'];
        }
        return ['status'=>200,'msg'=>$detail];
    }

    /**
     * 添加
     * @param array $detail
     * @return array
     */
    public static function addDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'purchase_code|单据编号'=>'require',
                'info_list|详细信息'=>'require',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $status = (new Commons())->checkCode($detail['purchase_code'],15);//验证编号是否合法
                if($status){
                    $adminId = (new Commons())->getAdminId();
                    if(empty($adminId)){
                        return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
                    }
                    $info_list = (array)json_decode($detail['info_list'], true);
                    $purchase_time = time();
                    $data = [];
                    foreach ($info_list as $k=>$v){
                        if(!empty($v['goods_id'])){//有产品
                            $data[] = [
                                'purchase_code'     =>  $detail['purchase_code'],
                                'purchase_time'     =>  $purchase_time,
                                'goods_type'        =>  $v['goods_type']===''?null:(float)$v['goods_type'],//商品类别
                                'goods_id'          =>  $v['goods_id']===''?null:(float)$v['goods_id'],
                                'stores_id'         =>  $v['stores_id']===''?null:(float)$v['stores_id'],
                                'goods_attr'        =>  $v['goods_attr']===''?null:(float)$v['goods_attr'],
                                'stock'             =>  $v['stock']===''?null:(float)$v['stock'],
                                'invertory_stock'   =>  $v['invertory_stock']===''?null:(float)$v['invertory_stock'],
                                'profit'            =>  $v['profit']===''?null:(float)$v['profit'],
                                'createtime'        => time(),
                                'updatetime'        => time(),
                            ];
                        }
                    }
                    if(!empty($data)){
                        $rowdata = [
                            'purchase_code'     =>  $detail['purchase_code'],
                            'purchase_time'     =>  $purchase_time,
                            'store_type'        =>  '1',
                            'createtime'        => time(),
                            'updatetime'        => time(),
                        ];
                    }else{
                        return ['status'=>500,'msg'=>'单据数据错误'];
                    }

                    $model = new Inventory();
                    $row = $model->where(['purchase_code'=>$detail['purchase_code']])->value('id');
                    if($row){
                        return ['status'=>500,'msg'=>'编号已存在'];
                    }
                    $result = false;
                    Db::startTrans();
                    try {
                        $model->allowField(true)->save($rowdata);
                        $result = $model->id;
                        if(!empty($data)){
                            Db::name('kuyou_inventory_info')->insertAll($data);
                        }
                        Db::commit();
                    } catch (Exception $e) {
                        Db::rollback();
                        return ['status'=>500,'msg'=>$e->getMessage()];
                    }
                    if($result){
                        return ['status'=>200,'msg'=>$detail['purchase_code']];
                    }else{
                        return ['status'=>500,'msg'=>'添加失败'];
                    }
                }else{
                    return ['status'=>500,'msg'=>'编号规则错误'];
                }
            }
        }
    }

    /**
     * 更新
     * @param array $detail
     * @return array
     */
    public static function editDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'old_purchase_code|原单据编号'=>'require',
                'purchase_code|单据编号'=>'require',
                'info_list|详细信息'=>'require',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $adminId = (new Commons())->getAdminId();
                if(empty($adminId)){
                    return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
                }
                $status = (new Commons())->checkCode($detail['purchase_code'],15);//验证编号是否合法
                if($status){
                    $model = new Inventory();
                    $row = $model->where(['purchase_code'=>$detail['old_purchase_code']])->find();
                    if(empty($row)){
                        return ['status'=>500,'msg'=>'修改的单据不存在'];
                    }
                    $info_list = (array)json_decode($detail['info_list'], true);

                    $purchase_time = time();
                    $data = [];
                    foreach ($info_list as $k=>$v){
                        if(!empty($v['goods_id'])){//有产品
                            $data[] = [
                                'purchase_code'     =>  $detail['purchase_code'],
                                'purchase_time'     =>  $purchase_time,
                                'goods_type'        =>  $v['goods_type']===''?null:(float)$v['goods_type'],//商品类别
                                'goods_id'          =>  $v['goods_id']===''?null:(float)$v['goods_id'],
                                'stores_id'         =>  $v['stores_id']===''?null:(float)$v['stores_id'],
                                'goods_attr'        =>  $v['goods_attr']===''?null:(float)$v['goods_attr'],
                                'stock'             =>  $v['stock']===''?null:(float)$v['stock'],
                                'invertory_stock'   =>  $v['invertory_stock']===''?null:(float)$v['invertory_stock'],
                                'profit'            =>  $v['profit']===''?null:(float)$v['profit'],
                                'createtime'        => time(),
                                'updatetime'        => time(),
                            ];
                        }
                    }
                    if(!empty($data)){
                        $rowdata = [
                            'purchase_code'     =>  $detail['purchase_code'],
                            'purchase_time'     =>  $purchase_time,
                            'store_type'        =>  '1',
                            'updatetime'        => time(),
                        ];
                    }

                    if($detail['purchase_code']!=$detail['old_purchase_code']){
                        $purchase_id = $model->where(['purchase_code'=>$detail['purchase_code']])->value('id');
                        if($purchase_id){
                            return ['status'=>500,'msg'=>'单据编号已使用，请重新输入单据编号'];
                        }
                    }

                    if($row){
                        $res = false;
                        Db::startTrans();
                        try {
                            $res = $model->where(['purchase_code'=>$detail['old_purchase_code']])->update($rowdata);
                            Db::name('kuyou_inventory_info')->where(['purchase_code'=>$detail['old_purchase_code']])->delete();
                            if(!empty($data)){
                                Db::name('kuyou_inventory_info')->insertAll($data);
                            }
                            Db::commit();
                        } catch (Exception $e) {
                            Db::rollback();
                            return ['status'=>500,'msg'=>$e->getMessage()];
                        }
                        if($res){
                            return ['status'=>200,'msg'=>'更新成功'];
                        }else{
                            return ['status'=>500,'msg'=>'更新失败'];
                        }
                    }else{
                        return ['status'=>500,'msg'=>'未查询到可更新数据'];
                    }
                }else{
                    return ['status'=>500,'msg'=>'编号规则错误'];
                }
            }
        }
    }

    /**
     * 删除
     * @param string $purchase_code
     * @return array
     */
    public static function delDetail($purchase_code){
        if(empty($purchase_code)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $purchase_code = explode(',',$purchase_code);
            $model = new Inventory();
            $list = $model->where(['purchase_code'=>['in',$purchase_code]])->select();

            $count = 0;
            $res = false;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $res = $model->where(['purchase_code'=>$v['purchase_code']])->delete();
                    $count += $res;
                    Db::name('kuyou_inventory_info')->where(['purchase_code'=>$v['purchase_code']])->delete();
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                return ['status'=>500,'msg'=>$e->getMessage()];
            }
            if($res){
                return ['status'=>200,'msg'=>$count];
            }else{
                return ['status'=>500,'msg'=>'删除失败'];
            }
        }
    }

    /**
     * 导出盘点数据
     * @return array
     */
    public static function export(){
        $list = Db::name('kuyou_goods_stock')->alias('gs')
            ->join('kuyou_goods g','g.id=gs.goods_id')
            ->where(['g.serial'=>['<>','1']])
            ->group('gs.goods_code,gs.attribute_id,gs.stores_id')
            ->field('sum(gs.stock) as stock,sum(gs.cost_money) as cost_money,gs.goods_code,gs.attribute_id,gs.stores_id')
            ->order('gs.goods_code ASC')
            ->select();

        foreach ($list as $list_k=>$list_v){
            $goods = Db::name('kuyou_goods')->where(['goods_code'=>$list_v['goods_code']])->field('id,goods_barcode,goods_name,goods_code,note,goods_type_id,goods_specification_id,unit_id')->find();
            $goods_type = Db::name('kuyou_goods_type')->where(['id'=>$goods['goods_type_id']])->field('id,supplier_type_name')->find();
            $stores = Db::name('kuyou_stores')->where(['id'=>$list_v['stores_id']])->field('id,name')->find();
            $list[$list_k]['goods'] = $goods;
            $list[$list_k]['goods_type'] = $goods_type;
            $list[$list_k]['stores'] = $stores;

            $attribute_ids = Db::name('kuyou_aux_combination')->where(['id'=>$list_v['attribute_id']])->value('attr_ids');
            if($attribute_ids){
                $attribute_ids = explode('&',$attribute_ids);
                $attribute = Db::name('kuyou_auxiliary')->where(['id'=>['in',$attribute_ids]])->column('name');
                $attribute_name = implode('/',$attribute);
                $list[$list_k]['attr_name'] = $attribute_name;
            }else{
                $list[$list_k]['attr_name'] = '';
            }

            $goods_attr = Db::name('kuyou_goods_attr')->where(['goods_code'=>$list_v['goods_code'],'attribute_id'=>$list_v['attribute_id']])->value('attr_code');
            $list[$list_k]['attr_code'] = $goods_attr;

            $unit = Db::name('kuyou_unit')->where(['id'=>$goods['unit_id']])->value('name');
            $list[$list_k]['unit_name'] = $unit;
        }

        $lists = [];
        foreach ($list as $list_k=>$list_v){
            $lists[] = [
                'stores_name' => $list_v['stores']['name'],
                'type_name' => $list_v['goods_type']['supplier_type_name'],
                'goods_code' => $list_v['goods']['goods_code'],
                'goods_name' => $list_v['goods']['goods_name'],
                'attr_code' => $list_v['attr_code'],
                'attr_name' => $list_v['attr_name'],
                'goods_spec' => $list_v['goods']['goods_specification_id'],
                'unit_name' => $list_v['unit_name'],
                'stock' => $list_v['stock'],
                'pstock' => '',
                'goods_barcode' => $list_v['goods']['goods_barcode'],
            ];
        }
        $title = [
            'stores_name' => '仓库',
            'type_name' => '商品类别',
            'goods_code' => '商品编号',
            'goods_name' => '商品名称',
            'attr_code' => '属性编号',
            'attr_name' => '属性名称',
            'goods_spec' => '规格型号',
            'unit_name' => '单位',
            'stock' => '系统库存',
            'pstock' => '盘点库存',
            'goods_barcode' => '商品条码',
        ];
        return ['title'=>$title,'list'=>$lists];
    }

}
